package com.zkingsoft.zkingbase.manager;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.zkingsoft.zkingbase.bean.resp.BaseResp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ytf on 2016/12/12.
 */
public class AliManager
{
    private static AliManager instance;
    private OkHttpManager httpManager;
    private Handler mHandler;
    private static Activity mContext;

    private AliManager(Activity context)
    {
        this.mContext = context;
        httpManager = OkHttpManager.getInstance();
    }

    /***
     * 拿到实例，此处的额Activity是方便创建支付任务的
     *
     * @param context
     * @return
     */
    public static AliManager getInstance(Activity context)
    {
        if (instance == null)
        {
            synchronized (AliManager.class)
            {
                if (instance == null)
                {
                    instance = new AliManager(context);
                }
            }
        }
        return instance;
    }

    /***
     * 发起支付宝支付,没有安装支付宝的跳转网页支付（未完善）
     * @param url 获取支付宝参数的后台接口
     * @param map 需要传递的参数， 1.传商品名称(subject)， 2.商品详情(body) ，3.价格(price)以元为单位
     * @param callback 回调接口
     */
    public void doPayWithClient(String url, Map<String, String> map, final AliPayResultCallBack callback)
    {
        if (callback == null)
        {
            throw new RuntimeException("Callback can't be null");
        }
        callback.onWait();

        httpManager.doPost(url, map, new OkHttpManager.ResultCallback<BaseResp>()
        {
            @Override
            public void onError(String simpleMsg, Exception e)
            {
                callback.onFailure(simpleMsg, e.getMessage());
            }

            @Override
            public void onSuccess(BaseResp response)
            {
                final String str = response.info;
                if (TextUtils.isEmpty(str))
                {
                    callback.onFailure("获取订单信息失败", "");
                } else
                {
                    List<String> lpkgs = getInstalledApps();
                    if(lpkgs.contains("com.aliyun.ams.tyid"))
                    {
                        new Thread()
                        {
                            @Override
                            public void run()
                            {
                                PayTask alipay = new PayTask(mContext);
                                // 调用支付接口，获取支付结果
                                Map<String, String> result = alipay.payV2(str, false);
                                Message msg = new Message();
                                msg.what = 1;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        }.start();
                    }else
                    {
                        callback.onFailure("未安装支付宝", "未安装支付宝");
                        return;
                    }


                    mHandler = new Handler(Looper.getMainLooper())
                    {
                        @Override
                        public void handleMessage(Message msg)
                        {
                            switch (msg.what)
                            {
                                case 1:
                                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
//                                    String resultInfo = payResult.getResult();

                                    String resultStatus = payResult.getResultStatus();

                                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                                    if (TextUtils.equals(resultStatus, "9000"))
                                    {
                                        callback.onComplete(resultStatus, "支付成功");
                                    } else
                                    {
                                        // 判断resultStatus 为非“9000”则代表可能支付失败
                                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                                        if (TextUtils.equals(resultStatus, "8000"))
                                        {
                                            callback.onComplete(resultStatus, "支付结果确认中");
                                        } else
                                        {
                                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                            callback.onFailure("支付失败,返回码:"+resultStatus, "返回码:"+resultStatus);
                                        }
                                    }
                                    mHandler.removeMessages(1);
                                    mHandler = null;
                                    break;
                            }
                        }
                    };
                }
            }
        });
    }

    private List<String> getInstalledApps()
    {
        List<String> res = new ArrayList<>();
        List<PackageInfo> packs = mContext.getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < packs.size(); i++)
        {
            PackageInfo p = packs.get(i);
            if (p.versionName == null)
            {
                continue;
            }
            res.add(p.packageName);
        }
        return res;
    }

    public interface AliPayResultCallBack
    {
        public void onComplete(String resultStatus, String resultDetailMsg);

        public void onFailure(String simpleMsg, String detail);

        public void onWait();
    }
}
